package Action.Manager;

import Action.Sys.Setting;
import Bean.*;
import Bean.Log.SystemLogEntity;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;
import org.hibernate.Session;
import tools.HibernateTools;
import tools.TimeTools;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.sql.Blob;
import java.util.LinkedList;
import java.util.List;

public class AltBookInfo extends ActionSupport {
    private int modify_id;
    private File book_picture_File;//上传文件的file对象，由拦截器自动填充
    private String book_picture_FileFileName;//上传文件名，由拦截器自动填充
    private String book_picture_FileContentType;//上传文件类型，由拦截器自动填充
    String book_name;
    String book_Author;
    String book_Info;
    String book_tag1;
    String book_tag2;
    String book_tags;
    Blob book_picture;
    int  vister;
    int sum;
    int used;
    BookInfoEntity bookInfoEntity;
    HttpServletRequest request;
    String err="";
    LinkedList<Object[]> loanBookLogRecords;
    LinkedList<Object[]> book_recomments;
    public String alt() {
        clearErrorsAndMessages();
        build_loanBookLogRecord();
        build_book_recomments();
        clearActionErrors();
        request = ServletActionContext.getRequest();
        Session session=HibernateTools.getSession();
        bookInfoEntity=session.get(BookInfoEntity.class, modify_id);
        //检查管理员权限
        if (!checkManage()) {
            addActionError("权限不足,请您先登录");
            request.getSession().setAttribute("message", "");
            return INPUT;
        }

        //数据合法性检查
        if (!BookDataCheck()){
            addActionError(err);
            request.getSession().setAttribute("message", "");
            return INPUT;
        }

        //数据封装
         getBookinfoEntity();
        //修改数据库
        session.saveOrUpdate(bookInfoEntity);


        addActionMessage("修改成功");
        bookInfoEntity.build_image(true);
        SystemLogEntity.addLog((Integer) ActionContext.getContext().getSession().get("adminid"), this, Setting.SystemLog_flag_AltBookData ,modify_id, SystemLogEntity.remark_book);
        HibernateTools.commit(session);
        return SUCCESS;
    }
    public String modify() throws Exception {
        bookInfoEntity=getBookInfo(modify_id);
        if (bookInfoEntity==null){
            bookInfoEntity=new BookInfoEntity();
            bookInfoEntity.setId(modify_id);
            bookInfoEntity.setBook_name("图书已不存在");
            bookInfoEntity.setBook_Info("图书已不存在,可查看本书原来的订单等信息");
        }else {
            bookInfoEntity.build_image(false);
        }
        Session session= HibernateTools.getSession();
//        session.saveOrUpdate(bookInfoEntity);
//        SystemLogEntity.addLog(new AdministratorEntity(), this, Setting.SystemLog_flag_AltBookData,bookInfoEntity.getBook_name());
        clearActionErrors();
        build_loanBookLogRecord();
        build_book_recomments();
        HibernateTools.commit(session);
        return SUCCESS;
    }

    private void build_book_recomments() {
        book_recomments=new LinkedList<>();
        Session session=HibernateTools.getSession();
        List<BookCommentEntity> commentEntities=session.createQuery("from BookCommentEntity where bookId=?")
                .setParameter(0, modify_id).setMaxResults(20).getResultList();
        for (BookCommentEntity commentEntity : commentEntities) {
            UserinfoEntity userinfoEntity=session.get(UserinfoEntity.class, commentEntity.getUserId());
            String username;
            if (userinfoEntity==null){
                username="用户不存在,原用户id为"+commentEntity.getUserId();
            }
            else {
                username=userinfoEntity.getUsername();
            }
            book_recomments.addLast(new String[]{username,TimeTools.timeStamp2Date(commentEntity.getDate(), null)
            ,commentEntity.getComment()});
        }
        HibernateTools.commit(session);

    }

    private BookInfoEntity getBookInfo(int id) {
        Session session=HibernateTools.getSession();
        return session.get(BookInfoEntity.class, id);
    }
    private void build_loanBookLogRecord() {
        Session session = HibernateTools.getSession();
        //显示最近10条图书订单
        loanBookLogRecords = new LinkedList<>();
        List<LoanBookLogRecord> middle=session.createQuery("from LoanBookLogRecord where bookId =? order by id desc ")
                .setParameter(0,modify_id).setMaxResults(10).getResultList();
        for (LoanBookLogRecord loanBookLogRecord : middle) {
            String id = "" + loanBookLogRecord.getId();
            BookInfoEntity bookInfoEntity = session.get(BookInfoEntity.class, loanBookLogRecord.getBookId());
            String bookname = bookInfoEntity == null ? "已删除图书ID:" + loanBookLogRecord.getUserId() : bookInfoEntity.getBook_name();
            UserinfoEntity userinfoEntity = session.get(UserinfoEntity.class, loanBookLogRecord.getUserId());
            String username = userinfoEntity == null ? "已删除用户ID:" + loanBookLogRecord.getUserId() : "" + loanBookLogRecord.getUserId();
            String orderTime = TimeTools.timeStamp2Date(loanBookLogRecord.getLoanTime(), null);
            String state = loanBookLogRecord.getState();
            String day = "" + loanBookLogRecord.getDay();
            Integer statepercentage = 0;
            if (state.equals(Setting.LoanBook_state_closed)) {
                statepercentage = 100;
            } else if (state.equals(Setting.LoanBook_state_reservation)) {
                statepercentage = 25;
            } else if (state.equals(Setting.LoanBook_state_need_TimeOut) || state.equals(Setting.LoanBook_state_need_Return)) {
                statepercentage = 75;
            } else {
                statepercentage = 100;//用户取消等情况
            }
            loanBookLogRecords.addLast(new Object[]{id, username, bookname, orderTime, day, state, statepercentage});
        }
        HibernateTools.commit(session);
    }


    private boolean BookDataCheck() {
        //数据完整度检测
        if (book_name==null||book_name.equals(""))
            err+="请输入书名\n";
        if (book_Author==null||book_Author.equals(""))
            err+="请输入作者\n";
        if (book_tag1==null||book_tag1.equals(""))
            err+="请至少填写一个标签\n";
        if (book_Info==null||book_Info.equals(""))
            err+="请输入完善图书简介\n";
        if (err.length()>0)
            return false;
        return true;
    }

    private boolean checkManage() {

        return true;
    }

    public BookInfoEntity getBookinfoEntity() {
        bookInfoEntity.setBook_name(book_name);
        bookInfoEntity.setBook_Author(book_Author);
        bookInfoEntity.setBook_Info(book_Info);
        bookInfoEntity.setBook_tag1(book_tag1);
        bookInfoEntity.setBook_tag2(book_tag2==null?"":book_tag2);
        bookInfoEntity.setSum(sum);
        bookInfoEntity.setVister(vister);
        bookInfoEntity.setUsed(used);
        if (book_picture_File!=null)
        bookInfoEntity.setBook_picture(HibernateTools.File_To_Blob(book_picture_File));
        return bookInfoEntity;
    }


    public int getModify_id() {
        return modify_id;
    }

    public void setModify_id(int modify_id) {
        this.modify_id = modify_id;
    }

    public File getBook_picture_File() {
        return book_picture_File;
    }

    public void setBook_picture_File(File book_picture_File) {
        this.book_picture_File = book_picture_File;
    }

    public String getBook_picture_FileFileName() {
        return book_picture_FileFileName;
    }

    public void setBook_picture_FileFileName(String book_picture_FileFileName) {
        this.book_picture_FileFileName = book_picture_FileFileName;
    }

    public String getBook_picture_FileContentType() {
        return book_picture_FileContentType;
    }

    public void setBook_picture_FileContentType(String book_picture_FileContentType) {
        this.book_picture_FileContentType = book_picture_FileContentType;
    }


    public String getBook_name() {
        return book_name;
    }

    public void setBook_name(String book_name) {
        this.book_name = book_name;
    }

    public String getBook_Author() {
        return book_Author;
    }

    public void setBook_Author(String book_Author) {
        this.book_Author = book_Author;
    }

    public String getBook_Info() {
        return book_Info;
    }

    public void setBook_Info(String book_Info) {
        this.book_Info = book_Info;
    }

    public String getBook_tag1() {
        return book_tag1;
    }

    public void setBook_tag1(String book_tag1) {
        this.book_tag1 = book_tag1;
    }

    public String getBook_tag2() {
        return book_tag2;
    }

    public void setBook_tag2(String book_tag2) {
        this.book_tag2 = book_tag2;
    }

    public String getBook_tags() {
        return book_tags;
    }

    public void setBook_tags(String book_tags) {
        this.book_tags = book_tags;
    }

    public Blob getBook_picture() {
        return book_picture;
    }

    public void setBook_picture(Blob book_picture) {
        this.book_picture = book_picture;
    }

    public int getVister() {
        return vister;
    }

    public void setVister(int vister) {
        this.vister = vister;
    }

    public int getSum() {
        return sum;
    }

    public void setSum(int sum) {
        this.sum = sum;
    }

    public int getUsed() {
        return used;
    }

    public void setUsed(int used) {
        this.used = used;
    }

    public HttpServletRequest getRequest() {
        return request;
    }

    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }

    public String getErr() {
        return err;
    }

    public void setErr(String err) {
        this.err = err;
    }

    public BookInfoEntity getBookInfoEntity() {
        return bookInfoEntity;
    }

    public void setBookInfoEntity(BookInfoEntity bookInfoEntity) {
        this.bookInfoEntity = bookInfoEntity;
    }

    public LinkedList<Object[]> getLoanBookLogRecords() {
        return loanBookLogRecords;
    }

    public void setLoanBookLogRecords(LinkedList<Object[]> loanBookLogRecords) {
        this.loanBookLogRecords = loanBookLogRecords;
    }

    public LinkedList<Object[]> getBook_recomments() {
        return book_recomments;
    }

    public void setBook_recomments(LinkedList<Object[]> book_recomments) {
        this.book_recomments = book_recomments;
    }
}
